<template>
  <div style="height: 6vh;background-color:#fff;padding: 10px 20px;">
    <span style="line-height:60px;font-size:20px;">员工管理</span>
    <el-button type="primary" style="float: right;margin-top: 10px;"
    @click="beforeAddemployee">新建员工</el-button>
  </div>
  <!-- 新建员工弹窗 -->
  <!-- :before-close="handleClose" 在弹窗关闭前先调用handleClose方法来处理弹窗的关闭问题
   避免点击弹窗外部也能关闭弹窗-->
  <el-dialog
    :title="dialogTitle"
    style="width: 1000px;padding: 40px;"
    v-model="dialogVisible"
    :before-close="handleClose"
  >
    <el-form label-position="top" label-width="80px">
     <el-row :gutter="10">
       <el-col :span="12">
         <el-form-item label="员工名">
           <el-input placeholder="请输入员工名" v-model="saveemployeeForm.employeeName"
           :disabled="saveemployeeForm.id != null"></el-input>
         </el-form-item>
       </el-col>
       <el-col :span="12">
         <el-form-item label="手机号">
           <el-input placeholder="请输入手机号" v-model="saveemployeeForm.phone"></el-input>
         </el-form-item>
       </el-col>
     </el-row>
      <el-row :gutter="10">
        <el-col :span="12">
          <el-form-item label="邮箱">
            <el-input placeholder="请输入邮箱" v-model="saveemployeeForm.email"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="年龄">
            <el-input placeholder="请输入年龄" v-model="saveemployeeForm.age"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="职级">
            <el-select placeholder="请选择" v-model="saveemployeeForm.level" @change="loadLeader">
              <el-option v-for="item in levelOptions"
                         :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="薪资">
            <el-input placeholder="请输入薪资" v-model="saveemployeeForm.salary"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="门店">
            <el-select v-model="saveemployeeForm.cinemaId" placeholder="请选择门店">
              <el-option v-for="item in cinemaList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="2">
        <el-col :span="6">
          <el-form-item label="性别">
            <el-radio-group v-model="saveemployeeForm.gender">
              <el-radio border label="男" value="1" style="margin:0;"></el-radio>
              <el-radio border label="女" value="0"></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="员工状态">
            <el-radio-group v-model="saveemployeeForm.status">
              <el-radio border label="启用" value="1" style="margin:0;"></el-radio>
              <el-radio border label="禁用" value="0"></el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="saveemployee">保存</el-button>
    </template>
  </el-dialog>

  <!-- 员工搜索卡片 -->
  <el-card style="margin: 20px;height: 70px;">
    <el-form :inline="true">
      <el-form-item label="员工搜索" style="width: 220px;">
        <el-input placeholder="输入员工名" v-model="searchemployeeForm.employeeName" @keydown.enter="loademployee"></el-input>
      </el-form-item>
      <el-form-item label="门店搜索" style="width: 220px;">
        <el-input placeholder="输入门店名" v-model="searchemployeeForm.name" @keydown.enter="loademployee"></el-input>
      </el-form-item>
      <el-form-item label="员工状态" style="width: 220px;">
        <el-select placeholder="请选择员工状态" v-model="searchemployeeForm.status" @change="loademployee">
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="resetSearch">重置</el-button>
        <el-button type="primary" @click="loademployee">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 员工表格卡片 -->
  <el-card style="margin: 20px;">
    <el-table :data="employeeArr">
      <el-table-column type="index" label="编号" width="80" align="center"></el-table-column>
      <el-table-column prop="employeeName" label="员工名" align="center"></el-table-column>
      <el-table-column prop="name" label="门店名" align="center"></el-table-column>
      <el-table-column prop="salary" label="薪资" align="center"></el-table-column>
      <el-table-column prop="phone" label="手机号" align="center"></el-table-column>
      <el-table-column prop="createTime" label="加入时间" align="center"></el-table-column>
      <el-table-column prop="status" label="员工状态" align="center">
        <template #default="scope">
          <!--  scope.row就代表表格中当前行的员工对象,也就是后端返回的employeeVO -->
          <el-switch active-value="1" inactive-value="0"
                     v-model="scope.row.status"
                     @change="changeStatus(scope.row.id,scope.row.status)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" >
        <template #default="scope">
          <el-button link type="primary" :disabled="scope.row.level==40"
                     @click="resetPassword(scope.row.id)">密码重置</el-button>
          <el-button link type="primary" :disabled="scope.row.level==40"
                     @click="editemployee(scope.row.id)">编辑</el-button>
          <el-button link type="primary" :disabled="scope.row.level==40"
                     @click="deleteemployee(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    ></el-pagination>
  </el-card>
</template>

<script setup>
import {computed, onMounted, ref} from "vue";
import axios from "axios";
import qs from "qs";
import {ElMessage} from "element-plus";

//定义变量控制弹窗是否出现
const dialogVisible = ref(false);
//定义变量用来控制弹窗的标题
const dialogTitle = ref('新建员工');

//定义数组用来维护员工职级的选项
const levelOptions = ref([
  {label:'员工',value:'10'},
  {label:'经理',value:'20'},
  {label:'总监',value:'30'},
  {label:'总裁',value:'40'},
]);

//定义对象用来收集保存表单的所有员工数据
const saveemployeeForm = ref({
  employeeName:'',
  phone:'',
  email:'',
  age:'',
  level:'',
  gender:'',
  status:'',
  salary:'',
  name:'',
  cinemaId:''
});
/* 点击"新建员工"按钮,出弹窗+修改弹窗标题 */
const beforeAddemployee = ()=>{
  dialogVisible.value = true;
  dialogTitle.value = '新建员工';
}
//定义保存员工的方法
const saveemployee = ()=>{
  console.log(saveemployeeForm.value);
  /* 安装查询字符串框架qs  npm install qs
  使用qs框架将JS对象转为查询字符串格式 name=tom&age=18,注意qs需要导入!!! import qs from "qs"; */
  let data = qs.stringify(saveemployeeForm.value);
  console.log(data);
  //向后端发送保存员工的请求
  /* 此处传的参数是qs转换后的查询字符串data,注意:使用了查询字符串,后端Controller不用加@RequestBody注解!!! */
  axios.post(BASE_URL+'/v1/employee/save',data)
      .then((response)=>{
        if(response.data.code == 2000){
          ElMessage.success('保存成功!');
          //关闭弹窗,并清空双向绑定的表单数据
          dialogVisible.value = false;
          saveemployeeForm.value = {};
          //保存成功后要重新加载员工数据!
          loademployee();
        }else{
          ElMessage.error(response.data.msg);
        }
      })
}
//处理弹窗关闭的方法
const handleClose = ()=>{
  if(confirm('您确认要关闭本窗口吗?')){
    //关闭弹窗,并清空双向绑定的表单数据
    dialogVisible.value = false;
    saveemployeeForm.value = {};
  }
}
const employeeArr = ref([]);
const searchemployeeForm = ref({employeeName:'', status:'',name:''});
const cinemaList  = ref({id:'',name:''});
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0)

const paginatedData = computed(() => {
  if (!Array.isArray(employeeArr.value)) return [];
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return employeeArr.value.slice(start, end);
});
//定义加载员工的方法
const loademployee = ()=>{
  let data =  qs.stringify({
    ...searchemployeeForm.value,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  });
  axios.get(BASE_URL+'/v1/employee/select?'+data)
      .then((response)=>{//回调函数中处理响应结果
        if(response.data.code == 2000){
          const pageInfo = response.data.data;
          employeeArr.value = pageInfo.list || []; // 将后端响应数据装入员工数组中
          total.value = pageInfo.total; // 更新总条数
          console.log(employeeArr.value);
        }else{
          ElMessage.error(response.data.msg);
        }
      })
}
const handleSizeChange = (newSize) => {
  pageSize.value = newSize;
  currentPage.value = 1; // 重置当前页为第一页
  loademployee();
};

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  loademployee();
};
const resetSearch = ()=>{
  //清空之前的搜索条件
  searchemployeeForm.value = {};
  //重新加载所有的员工数据
  loademployee();
}

/* 页面一加载完毕,立即执行 */
onMounted(()=>{
  loademployee();
  loadcinema();
})
//定义对象用来保存员工的查询条件

const loadcinema = () =>{
  axios.get(BASE_URL+'/v1/cinemas/select').then((response)=>{
    if (response.data.code == 2000){
      cinemaList.value = response.data.data; // 假设后端返回的数据结构中包含 data 数组
    }else {
      ElMessage.error(response.data.msg);
    }
  })
}
//定义重置搜索条件的方法




//定义重置密码的方法 restful风格
const resetPassword = (employeeId)=>{
  axios.post(BASE_URL+'/v1/employee/update/password/'+employeeId)
      .then((response)=>{
        if(response.data.code == 2000){
          ElMessage.success('密码重置成功!');
        }else{
          ElMessage.error(response.data.msg);
        }
      })
}

//定义编辑员工的方法
const editemployee = (id)=>{
  //出弹窗 + 修改弹窗标题
  dialogVisible.value = true;
  dialogTitle.value = '编辑员工';
  //根据员工id查询当前员工的详细数据显示在弹窗表单中
  axios.get(BASE_URL+'/v1/employee/selectById?id='+id).then((response)=>{
    if(response.data.code == 2000){
      //注意:后端返回的是List<employeeVO>,所以查一条数据的话拿的是集合的第1个元素,data[0]等价list.get(0)
      saveemployeeForm.value = response.data.data;
      console.log(saveemployeeForm.value)
    }else{
      ElMessage.error(response.data.msg);
    }
  })
}

//定义修改员工状态的方法
const changeStatus = (employeeId,status)=>{
  axios.post(BASE_URL+'/v1/employee/update/status/'+employeeId+'/'+status)
      .then((response)=>{
        if(response.data.code == 2000){
          ElMessage.success('修改状态成功!');
        }else{
          ElMessage.error(response.data.msg);
        }
      })
}
//查找影城数据

//创建删除员工的方法
const deleteemployee = (employeeId)=>{
  if(confirm('您确认要删除该员工吗?')){
    axios.post(BASE_URL+'/v1/employee/delete/'+employeeId)
        .then((response)=>{
      if(response.data.code == 2000){
        ElMessage.success('删除成功!');
        loademployee();//重新加载员工数据
      }else{
        ElMessage.error(response.data.msg);
      }
    })
  }
}
</script>

<style scoped>
/* 添加一些基本样式 */
.el-card {
  margin: 20px;
}

.el-table {
  width: 100%;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}
</style>